<template>
  <div class="border-1 border-solid border-#e4e4e4 p-2">
    <div class="flex">
      <div class="upload-left" :style="'height:' + height" @click="handleClick">
        <div class="font-size-3">{{ title }}</div>
        <div class="upload-icon">
          <div class="color-#8d8d8d font-size-10">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          </div>
          <div class="upload-text">支持{{ accept }}格式</div>
        </div>
      </div>
      <el-scrollbar :style="'height:' + height + ';width:100%'" class="ml-2">
        <div v-for="(item, index) in files" :key="'file-item' + index" class="color-#8d8d8d font-size-3 line-height-6">
          {{ item.name }}
        </div>
      </el-scrollbar>
    </div>
    <el-dialog v-if="dialogVisible" v-model="dialogVisible" :title="title" width="1000px" :before-close="handleClose">
      <div class="border-1 border-solid border-#e4e4e4 p-2">
        <el-scrollbar style="height: 300px">
          <div v-for="(item, index) in fileList" :key="'file-item' + index" class="flex flex-justify-between flex-items-center">
            <div class="w-200 color-#8d8d8d">{{ item.name }}</div>
            <div v-if="!loading" class="cursor-pointer pr-3" @click="handleRemove(index)">
              <el-icon color="#8d8d8d" :size="20"><Close /></el-icon>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <div class="flex flex-justify-between">
        <el-upload
          v-model:file-list="fileList"
          class="mt-2"
          :auto-upload="false"
          action="#"
          multiple
          :accept="accept"
          :limit="limit"
          :on-exceed="handleExceed"
          :show-file-list="false"
        >
          <el-button type="primary" :disabled="loading">选择上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持{{ accept }}格式</div>
          </template>
        </el-upload>
        <div class="mt-4">已选择{{ fileList.length }}份文件</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-loading="loading" type="primary" @click="handleSubmit">提交</el-button>
          <el-button v-loading="loading" @click="handleClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TaskUpload" lang="ts">
import { uploadLoadExperiment } from '@/api/loadProcessingAlgorithm/loadTaskManagement/index';
import type { UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const prop = defineProps({
  title: {
    type: String,
    default: '上传原始载荷'
  },
  height: {
    type: String,
    default: '120px'
  },
  accept: {
    type: String,
    default: '.dat,.xls,.xlsx'
  },
  limit: {
    type: Number,
    default: 90
  },
  modelValue: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  },
  loadExperimentId: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['update:modelValue', 'update-file']);
const dialogVisible = ref(false);
const fileList = ref([]);
const files = ref([]);
const loading = ref(false);
const checkedFile = () => {
  let flag = true;
  for (let i = 0; i < fileList.value.length; i++) {
    const fileName = fileList.value[i].name;
    const fileType = fileName.substring(fileName.lastIndexOf('.')).toLocaleLowerCase();
    if (!prop.accept.includes(fileType)) {
      flag = false;
      break;
    }
  }
  return flag;
};
const handleClick = () => {
  if (prop.disabled) {
    proxy?.$modal.msgWarning('不支持修改！');
    return false;
  }
  fileList.value = [];
  dialogVisible.value = true;
};
const handleClose = () => {
  dialogVisible.value = false;
};
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`当前限制${prop.limit}, 你选择了这次选择了 ${files.length} 个文件, 共选择了${files.length + uploadFiles.length}文件`);
};
const handleRemove = async (index) => {
  await proxy?.$modal.confirm('是否确认删除该文件?');
  fileList.value.splice(index, 1);
};
const handleSubmit = async () => {
  if (!checkedFile()) {
    proxy?.$modal.msgError('请选择正确的文件类型');
    return;
  }
  if (prop.loadExperimentId) {
    loading.value = true;
    const formData = new FormData();
    formData.append('parameterName', prop.name);
    formData.append('loadExperimentId', prop.loadExperimentId);
    fileList.value.forEach((item) => {
      formData.append('files', item.raw);
    });
    await uploadLoadExperiment(formData).catch(() => {
      loading.value = false;
    });
    files.value = fileList.value;
    emit('update:modelValue', files.value.map((item) => item.name).join(','));
    emit('update-file');
    handleClose();
    loading.value = false;
  } else {
    proxy?.$modal.msgError('请先选择版本号');
  }
};
watch(
  () => prop.modelValue,
  () => {
    if (prop.modelValue) {
      files.value = prop.modelValue.split(',').map((item) => ({ name: item }));
    }
  }
);
onMounted(() => {
  if (prop.modelValue) {
    files.value = prop.modelValue.split(',').map((item) => ({ name: item }));
  }
});
</script>

<style lang="scss" scoped>
.upload-left {
  border-right: 1px solid #e4e4e4;
  width: 150px;
  position: relative;
  cursor: pointer;
}
.upload-icon {
  position: absolute;
  top: 50%;
  text-align: center;
  transform: translate(10px, -50%);
}
.upload-text {
  font-size: 10px;
  color: #8d8d8d;
}
.dialog-footer {
  text-align: center;
}
</style>
